﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class AdminDetalhesProduto : System.Web.UI.Page
{
    // store product and category IDs as class members
    private string currentProductId, currentCategoryId, currentEmpresaId;

    protected void Page_Load(object sender, EventArgs e)
    {
        currentCategoryId = Request.QueryString["Categoria"];
        currentProductId = Request.QueryString["ProdutoID"];
        currentEmpresaId = Request.QueryString["EmpresaID"];

        this.Title = AcheiCampinasConfiguration.SiteName +
            " : detalhes do produto ou serviço.";

        // Fill the controls with data only on the initial page load
        if (!IsPostBack)
        {
            // Fill controls with data
            PopulateControls();
        }
    }

    // Populate the controls
    private void PopulateControls()
    {
        // Retrieve product details and category details from database
        DetalhesProduto productDetails = CatalogAccess.GetDetalhesProduto(currentProductId);
        DetalhesCategoria categoryDetails = CatalogAccess.GetDetalhesCategoria(currentCategoryId);

        // Set up labels and images
        productNameLabel.Text = productDetails.Nome;
        image1.ImageUrl = Link.ToProductImage(productDetails.Imagem1);
        image2.ImageUrl = Link.ToProductImage(productDetails.Imagem2);
        image3.ImageUrl = Link.ToProductImage(productDetails.Imagem3);

        // Clear form
        categoriesLabel.Text = categoryDetails.Nome;
        categoriesListMove.Items.Clear();

        // Fill categoriesLabel and categoriesListRemove with data
        string categoryId, categoryName;
                        
        // Fill categoriesListMove and categoriesListAssign with data
        DataTable productCategories = CatalogAccess.GetCategoriasSemEsteProduto(currentProductId);

        // Delete from catalog or remove from category?
        if (productCategories.Rows.Count == 1)
        {
            deleteButton.Visible = false;
        }
        else
        {
            deleteButton.Visible = true;
        }

        for (int i = 0; i < productCategories.Rows.Count; i++)
        {
            // obtain category id and name
            categoryId = productCategories.Rows[i]["CategoriaID"].ToString();
            categoryName = productCategories.Rows[i]["Nome"].ToString();
            // populate the list boxes
            categoriesListMove.Items.Add(new ListItem(categoryName, categoryId));

        }
    }

    // delete a product from the catalog
    protected void deleteButton_Click(object sender, EventArgs e)
    {
        // Delete the product from the catalog
        CatalogAccess.DeleteProduct(currentProductId);
        // Need to go back to the categories page now
        Response.Redirect("Mensagens.aspx?n=4");
    }

    // move the product to another category
    protected void moveButton_Click(object sender, EventArgs e)
    {
        // Check if a category was selected
        if (categoriesListMove.SelectedIndex != -1)
        {
            // Get the category ID that was selected in the DropDownList
            string newCategoryId = categoriesListMove.SelectedItem.Value;
            // Move the product to the category
            bool success = CatalogAccess.MoveProductToCategory(currentProductId, newCategoryId);
            // If the operation was successful, reload the page, 
            // so the new category will reflect in the query string
            if (!success)
                statusLabel.Text = "Não foi possível trocar o produto de categoria.";
            else
                Response.Redirect("AdminDetalhesProduto.aspx" + "?Categoria=" + newCategoryId + "&ProdutoID=" + currentProductId);
        }
        else
            statusLabel.Text = "Você precisa selecionar uma categoria.";
    }

    // upload product's first image
    protected void upload1Button_Click(object sender, EventArgs e)
    {
        // proceed with uploading only if the user selected a file
        if (image1FileUpload.HasFile)
        {
            try
            {
                string fileName = image1FileUpload.FileName;
                string location = Server.MapPath("./ImagensProdutos/") + fileName;
                // save image to server
                image1FileUpload.SaveAs(location);
                // update database with new product details
                DetalhesProduto pd = CatalogAccess.GetDetalhesProduto(currentProductId);
                CatalogAccess.UpdateProductImage(currentProductId, fileName, "1");
                // reload the page 
                Response.Redirect("AdminDetalhesProduto.aspx" +
                        "?Categoria=" + currentCategoryId +
                        "&ProdutoID=" + currentProductId);
            }
            catch
            {
                statusLabel.Text = "Falha no upload da 1ª imagem.";
            }
        }
    }

    // upload product's second image
    protected void upload2Button_Click(object sender, EventArgs e)
    {
        // proceed with uploading only if the user selected a file
        if (image2FileUpload.HasFile)
        {
            try
            {
                string fileName = image2FileUpload.FileName;
                string location = Server.MapPath("./ImagensProdutos/") + fileName;
                // save image to server
                image2FileUpload.SaveAs(location);
                // update database with new product details
                DetalhesProduto pd = CatalogAccess.GetDetalhesProduto(currentProductId);
                CatalogAccess.UpdateProductImage(currentProductId, fileName, "2");
                // reload the page 
                Response.Redirect("AdminDetalhesProduto.aspx" +
                        "?Categoria=" + currentCategoryId +
                        "&ProdutoID=" + currentProductId);
            }
            catch
            {
                statusLabel.Text = "Falha no upload da 2ª imagem.";
            }
        }
    }

    // upload product's second image
    protected void upload3Button_Click(object sender, EventArgs e)
    {
        // proceed with uploading only if the user selected a file
        if (image3FileUpload.HasFile)
        {
            try
            {
                string fileName = image3FileUpload.FileName;
                string location = Server.MapPath("./ImagensProdutos/") + fileName;
                // save image to server
                image3FileUpload.SaveAs(location);
                // update database with new product details
                DetalhesProduto pd = CatalogAccess.GetDetalhesProduto(currentProductId);
                CatalogAccess.UpdateProductImage(currentProductId, fileName, "3");
                // reload the page 
                Response.Redirect("AdminDetalhesProduto.aspx" +
                        "?Categoria=" + currentCategoryId +
                        "&ProdutoID=" + currentProductId);
            }
            catch
            {
                statusLabel.Text = "Falha no upload da 3ª imagem.";
            }
        }
    }

    protected void deleteFile(String filename)
    {
        // Delete a file by using File class static method...
        if (System.IO.File.Exists(Server.MapPath("./ImagensProdutos/") + filename))
        {
            // Use a try block to catch IOExceptions, to
            // handle the case of the file already being
            // opened by another process.
            try
            {
                System.IO.File.Delete(Server.MapPath("./ImagensProdutos") + filename);
            }
            catch (System.IO.IOException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
        }
    }

}